using System;
using System.IO.Ports;

namespace ElevatorLib
{
	public class AbstractElevatorImplementation : AbstractElevatorFacade
	{
        private ElevatorFeedbackFacade feedback;
        private SerialWriteFacade serialWrite;

        [Obsolete("Workaround while not having SerialRead")]
        private SerialPort port;

		public AbstractElevatorImplementation (SerialPort port, ElevatorFeedbackImplementation fb)
		{
            serialWrite = new SerialWriteImplementation(port);
            feedback = fb;
            this.port = port;
            if (port.IsOpen) port.Close();
            port.DataReceived += new SerialDataReceivedEventHandler(rs232_DataReceived);
            port.Open();
		}
		
		public void CallEmergency()
		{
            serialWrite.Write(0x0E);
		}

	    public void GoTo(int floor)
		{
			switch(floor)
			{
			case 0:
                serialWrite.Write(0x01);
				break;
			case 1:
                serialWrite.Write(0x02);
				break;
			case 2:
                serialWrite.Write(0x03);
				break;
			case 3:
                serialWrite.Write(0x04);
				break;
			}
		}
	
	    public void ResumeOperations()
		{
            serialWrite.Write(0x0F);
		}

        #region DataReceived
        /// <summary>
        /// Eventhandler to handle all incoming data.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void rs232_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            this.ParseMessage((byte)this.port.ReadByte());
        }
        #endregion


        public void ParseMessage(byte message)
		{
            // TODO add 0x0f?

            switch (message)
			{
				case 0xF1:
                    feedback.ArrivedAt(0);
                    break;
                case 0xF2:
                    feedback.ArrivedAt(1);
                    break;
                case 0xF3:
                    feedback.ArrivedAt(2);
                    break;
                case 0xF4:
                    feedback.ArrivedAt(3);
                    break;
                case 0x01:
                    feedback.MovingTo(0);
                    break;
                case 0x02:
                    feedback.MovingTo(1);
                    break;
                case 0x03:
                    feedback.MovingTo(2);
                    break;
                case 0x04:
                    feedback.MovingTo(3);
                    break;
                case 0x0E:
                    feedback.NewEmergency();
                    break;
                case 0x0F:
                    feedback.ResumeOperations();
                    break;
                default:
                    feedback.ArrivedAt(2);
                    break;
			}
		}
	
	}
}

